<?php

   require_once "config.php";
   require_once "debug.php";

    //TODO Use Google Gears

    $tagName = @$_GET['tagName'];
    $settingsUrl = @$_SERVER['HTTP_REFERER'];
    $deleteTag = @$_GET['deleteTag'];

    if (($tagName != "") && ($settingsUrl != ""))
    {
        if ($deleteTag == 1)
        {
           //delete tag
           if (deleteRecentSetting($tagName))
           {
                echo "OK";
           }
           else
           {
                echo "FAILED TO DELETE TAG: " . $tagName;
           }
        }
        else
        {
            //add tag
            if (addRecentSetting(time(), $tagName, $settingsUrl, true))
            {
                debugMsg("Tagged url ".$settingsUrl . " as ".$tagName);
                echo "OK";
            }
            else
            {
                debugMsg("Failed to add tag ".$tagName);
                echo "DUPLICATE";
            }
        }
    }


    function deleteRecentSetting($tagName)
    {
        try
        {
            $newSettings = "";

            $lines = file($GLOBALS['settingsTagsFile']);
            for ($i=0; $i<count($lines); $i++)
            {
                $dateAndUrl = explode("\t", $lines[$i]);
                if (trim($dateAndUrl[1]) != $tagName)
                {
                    $newSettings .= $lines[$i];
                }
            }

            $fpus = fopen ($GLOBALS['settingsTagsFile'], "w");
            fwrite ($fpus, $newSettings);
            fclose ($fpus);

            return true;
        }
        catch (Exception $err)
        {
            return false;
        }

    }

    function readRecentSettings()
    {

    }

    function addRecentSetting($dateTime, $gadgetTitle, $url, $isUserTag=false)
    {
            if ($url == "")
            {
                return;
            }

            $settingsFile = $isUserTag ? $GLOBALS['settingsTagsFile'] : $GLOBALS['recentSettingsFile'];

            $url = substr($url, strlen($GLOBALS['IGLocalDir']));

            if (stristr($gadgetTitle, "http://"))
            {
                $gadgetTitle = basename($gadgetTitle);
            }

            if (recentSettingExists($gadgetTitle, $settingsFile))
            {
                return false;
            }


            $fp = fopen ($settingsFile, "a");
            fwrite ($fp, $dateTime ."\t".$gadgetTitle."\t".$url ."\r\n");
            fclose ($fp);

            return true;
    }


    function recentSettingExists($tag, $settingsFile)
    {
        $allRecentSettingsHandle = fopen($settingsFile, "r");
        $line = "";
        $found = false;
        while (!feof($allRecentSettingsHandle))
        {
            $line = fgets($allRecentSettingsHandle);

            if ($line != "")
            {

                $dateAndUrl = explode("\t", $line);
                if (trim($dateAndUrl[1]) == $tag)
                {
                    $found = true;
                }
            }

        }
        fclose($allRecentSettingsHandle);
        return $found;
    }

    function getRecentSettings($count)
    {
        $allRecentSettingsHandle = fopen($GLOBALS['recentSettingsFile'], "r");
        $line = "";
        $html = "<table id='recentSettingsTable' width='100%' cellpadding='0' cellspacing='0'>";
        $rows = "";
        $i=0;

        while (!feof($allRecentSettingsHandle) && ($i < $count))
        {
            $line = fgets($allRecentSettingsHandle);

            if ($line != "")
            {

                $dateAndUrl = explode("\t", $line);
                $t = trim($dateAndUrl[0]);
                $time = date("d/m/y H:i", $t);
                $gadget = trim($dateAndUrl[1]);
                $link = trim($dateAndUrl[2]);
                $link = $GLOBALS['IGPath'] . $link;

                $rows = "<tr><td>&nbsp;&nbsp;<a href=".$link.">".$gadget."</a></td><td align='right'>&nbsp;".$time."</td></tr>" . $rows;
                $i++;
            }
        }

        $userTags = fopen($GLOBALS['settingsTagsFile'], "r");
        $line = "";

        while (!feof($userTags))
        {
            $line = fgets($userTags);

            if ($line != "")
            {

                $dateAndUrl = explode("\t", $line);
                $t = trim($dateAndUrl[0]);
                $time = date("d/m/y H:i", $t);
                $gadget = trim($dateAndUrl[1]);
                $link = trim($dateAndUrl[2]);
                $link = $GLOBALS['IGPath'] . $link;

                $rows = "<tr><td>&nbsp;&nbsp;<a href=".$link.">".$gadget."</a></td><td align='right'>&nbsp;<a href='javascript:void(0)' onclick='addTag(\"" . $gadget ."\", this);'>delete this tag</a></td></tr>" . $rows;
                $i++;
            }
        }

        fclose($allRecentSettingsHandle);
        $html .= $rows;
        $html .= "</table>";
        $html .= "</table>";
        return $html;
    }

    function updateRecentSetting($url)
    {

    }

	function writeLocalDeveloper($gadget, $moduleId)
	{
?>
<script src="js/recentSettings.js"></script>
<div id="m_<?php echo $moduleId;?>" class="modbox<?php echo (@$_GET['pinSettings'] == 1) ? "_e" : "";?> ">
	<h2 class="modtitle">
		<a class="delbox" href="javascript:void(0)" onclick="return _del('<?php echo $moduleId; ?>',32,'n_32=url%3Dhttp://myearnings.googlecode.com/svn/trunk/MyEarnings.xml%26up_salaryH%3D20000%26up_salary%3D********%26up_timerPaused%3D1%26up_timerStart%3D6422');"></a><a class="minbox" id="m_<?php echo $moduleId;?>_zippy" href="javascript:void(0)" onclick="this.blur();return _zm('<?php echo $moduleId; ?>', '32');return false;"></a>


		<span class="my_gadget" style="display:none"></span>

		<div id="m_<?php echo $moduleId;?>_h">
			<a class="mtlink" id="m_<?php echo $moduleId;?>_url" href="http://bonstio.net">
				<span id="m_<?php echo $moduleId;?>_title" class="modtitle_text">Local Developer</span>
			</a>
		</div>
	
	</h2>
	<div id="m_<?php echo $moduleId;?>_b" class="modboxin">

		<!-- Copyright 2007 and beyond, Google Inc.  To use gadgets on your own site, visit http://www.google.com/webmasters/gadgets.  To create your own gadgets, visit http://www.google.com/apis/gadgets -->
            <table border=0 cellpadding=0 cellspacing=0 width=95% align=center>
			<tr>
				<td width="35%" align="right" colspan="1">Gadget filename</td>
				<td width="65%" nowrap="" align="left" colspan="2">&nbsp;
					<input type="text" value="<?php echo (@$_GET['gadget']);?>" name="gadget" id="gadgetUrl" maxlen="200" size="20"/>
				</td>
			</tr>
			<tr>
				<td colspan=1 align=right width="35%">Pin open settings</td>
				<td colspan=2 nowrap align=left width="65%">&nbsp;
					<input type=hidden id=pinSettings name=pinSettings value=<?php echo (@$_GET['pinSettings'] == 1) ? "1" : "0";?>>
					<input type=checkbox <?php echo (@$_GET['pinSettings'] == 1) ? "CHECKED" : "UNCHECKED";?> onClick="_gel('pinSettings').value = this.checked ? '1' : '0';"/> 
				</td>
			</tr>
			<tr>
				<td colspan=1 align=right width="35%">Use local cache</td>
				<td colspan=2 nowrap align=left width="65%">&nbsp;
					<input type=hidden id=offline name=offline value=<?php echo (@$_GET['offline'] == 1) ? "1" : "0";?>>
					<input type=checkbox <?php echo (@$_GET['offline'] == 1) ? "CHECKED" : "UNCHECKED";?> onClick="_gel('offline').value = this.checked ? '1' : '0';"/> 
				</td>
			</tr>
            <tr>
				<td valign=top colspan=1 align=right width="35%">Force gadget requests through proxy</td>
				<td colspan=2 nowrap align=left width="65%">
				<font size="1">
                    &nbsp;<INPUT TYPE=RADIO NAME="useProxy" <?php echo (@$_GET['useProxy'] == 0) ? "CHECKED" : "UNCHECKED";?> VALUE="0">Off
                    <br/>
                    &nbsp;<INPUT TYPE=RADIO NAME="useProxy" <?php echo (@$_GET['useProxy'] == 1) ? "CHECKED" : "UNCHECKED";?> VALUE="1">On
                    <br/>
                    &nbsp;<INPUT TYPE=RADIO NAME="useProxy" <?php echo (@$_GET['useProxy'] == 2) ? "CHECKED" : "UNCHECKED";?> VALUE="2">Render gadget via gmodules
                </font>
				</td>
			</tr>
			<tr>
				<td colspan=1 valign=top align=right width="35%">Configuration history</td>
				<td valign=top colspan=2 align=left width="65%">
				   <table width="100%" cellpadding="0" cellspacing="0">
				           <tr>
                                <td>&nbsp;
                                <input style="color:#cccccc" type="text" value="Tag current config..." name="configTag" id="configTag" maxlen="200" size="20" onclick="focusTag(this);" onblur="blurTag(this);"/></td>
                                <td align="right">
                                <font size="1">
                                    <a href="javascript:void(0)" style="color:#cccccc" id="tagadd" onclick="this.blur();addTag(_gel('configTag').value);">add tag</a>
                                </font>
                                </td>
                            </tr>
			
				   </table>
				</td>
			</tr>

				<td colspan=1 valign=top align=right width="35%"></td>
				<td colspan=2 nowrap align=left width="65%">
				    <font size="1">
                        <?php echo getRecentSettings($GLOBALS['settingsHistoryLimit']); ?>
                    </font>
                    <br/>
				</td>
			</tr>
			</table>
            <table border=0 cellpadding=0 cellspacing=0 width=95% align=center>
                <tr>
                    <td colspan=2 nowrap align=left><br><a href=""><font size=-1 color=#7777cc></font></a></td>
                    <td colspan=1 align=right valign=bottom>
<?php
                    if (isUsingExternalGadgetFiles())
                    {
?>
                       <input type=button value="Download gadget XML" onclick="document.location = '<?php echo $GLOBALS['IGLocalDir'].$GLOBALS['generatedDir'].$GLOBALS['gadgetFileName']?>'">               
<?php
                    }
?>
						<input id=save_<?php echo $moduleId;?> class=submitbtn type=submit value="Save settings">
                    </td>
                </tr>
            </table>
	</div>
</div>
<?php
	}
?>